package com.luyang.platform.contact.application.user.ability;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.CharSequenceUtil;
import com.luyang.framework.ddd.ability.BaseAbility;
import com.luyang.framework.protocol.Result;
import com.luyang.platform.contact.application.user.command.CreateUserCommand;
import com.luyang.platform.contact.domain.user.repository.IUserRepository;
import com.luyang.platform.contact.domain.user.valueobject.Mobile;
import com.luyang.platform.contact.domain.user.valueobject.UserId;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.validation.ValidationException;

/**
 * 创建用户能力
 *
 * @author lu_yang
 */
@Service
@RequiredArgsConstructor
public class UserCreateAbility extends BaseAbility<CreateUserCommand, Void> {

    private final IUserRepository userRepository;

    @Override
    public void checkHandler(CreateUserCommand cmd) {
        // 校验手机号是否存在
        Assert.isNull(this.userRepository.find(new Mobile(cmd.mobile())),
            () -> new ValidationException("手机号已注册"));

        // 校验上级ID是否有效
        Assert.notNull(this.userRepository.find(new UserId(cmd.leaderUserId())),
            () -> new ValidationException(
                CharSequenceUtil.format("未查询到上级信息, 上级userId:{}", cmd.leaderUserId())
            ));
        // TODO: 2022/5/13 校验部门是否存在
    }

    @Override
    public Result<Void> checkIdempotent(CreateUserCommand abilityCmd) {
        return Result.success();
    }

    @Override
    public Result<Void> execute(CreateUserCommand abilityCmd) {
        // TODO: 2022/5/14 构建领域模型，入库账号信息、用户信息、部门信息、发布用户创建事件
        return null;
    }
}
